/**
 * 初始化页面
 */
$(document).ready(function () {
    // 页面显示时间
    nowTime();
    setInterval(nowTime, 1000);

    // 左边菜单栏收起
    $('.leftbtnbox .leftbtn').click(function () {
        $('.jiantou').toggleClass("change");
        if ($('.leftbtnbox').css('left') == '0px') {
            $('.leftbtnbox').stop(true).animate({left: '140px'});
            $('.leftnavcard').stop(true).animate({width: '220px'}, "slow", function () {
            });
            $('.rightiframe').css({left: '220px', paddingLeft: "0px"});
            $('.leftbtn').css('background', '');
        }
        else {
            $('.leftbtnbox').stop(true).animate({left: '0px'});
            $('.leftnavcard').stop(true).animate({width: '0'}, "slow", function () {
            });
            $('.rightiframe').css({left: '0px', paddingLeft: "55px"});
            $('.leftbtn').css('background', '#fff');
        }
    });

    // 初始化导航菜单
    loadNavigation();

    $(window).resize(function () {
        resizeLeftnavcard();
    });

});

/**
 * 格式化当前时间用于显示
 */
function nowTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = month > 9 ? month : '0' + month;
    var day = date.getDate();
    day = day > 9 ? day : '0' + day;
    var hour = date.getHours();
    hour = hour > 9 ? hour : '0' + hour;
    var minute = date.getMinutes();
    minute = minute > 9 ? minute : '0' + minute;
    var second = date.getSeconds();
    second = second > 9 ? second : '0' + second;
    var week = date.getDay();
    switch (week) {
        case 1:
            week = "星期一 ";
            break;
        case 2:
            week = "星期二 ";
            break;
        case 3:
            week = "星期三 ";
            break;
        case 4:
            week = "星期四 ";
            break;
        case 5:
            week = "星期五 ";
            break;
        case 6:
            week = "星期六 ";
            break;
        case 0:
            week = "星期日 ";
            break;
        default:
            week = "";
            break;
    }
    $('#now-time').html(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second + ' ' + week)
}

/**
 * 初始化导航菜单
 */
function loadNavigation() {
    $.ajax({
        type: 'post',
        async: true,// 异步请求
        url: ctx + '/index/findSubModule',
        dataType: 'json',
        data: {
            parentCode: '000'
        },
        success: function (res) {
            if (res.success) {
                createNavigationHtml(res.result);
            }
        }
    });
}

/**
 * 构造导航菜单
 *
 * @param data
 */
function createNavigationHtml(data) {
    // var navigationHtml = '<a id="homepage" href="javascript:void(0)" onclick="jumpPage(\'' + ctx + '/index/home\',\'1\',this);" class="item">首页</a>';
    var navigationHtml = '<a id="homepage" href="javascript:void(0)" onclick="jumpPage(\''+ ctx + '/kpiContrast/host_database_middleware/100\',\'1\',this);" class="item">首页</a>';
    $.each(data, function (idx, item) {
        navigationHtml += '<a href="javascript:void(0)" onclick="loadAccordion(\'' + item.moduleCode + '\',this);" class="item">' + item.moduleName + '</a>';
    });
    $('#navigation').html(navigationHtml);

    // 默认加载首页
    $('#homepage').trigger('click');
}

/**
 * 加载折叠面板菜单
 *
 * @param moduleCode
 * @param obj
 */
function loadAccordion(moduleCode, obj) {
    // 展开左侧菜单
    if ($('.leftbtnbox').css('left') == '0px') {
        $('.leftbtnbox .leftbtn').trigger('click');
    }
    // 切换导航选中样式
    triggerNavigationCss(obj);

    $.ajax({
        type: 'post',
        async: true,// 异步请求
        url: ctx + '/index/findSubModule',
        dataType: 'json',
        data: {
            parentCode: moduleCode
        },
        success: function (res) {
            if (res.success) {
                createAccordionHtml(res.result);
            }
        }
    });
}

/**
 * 构造折叠面板菜单
 *
 * @param data
 */
function createAccordionHtml(data) {
    var accordionHtml = '';
    $.each(data, function (idx, item) {
        accordionHtml += '<h3 id="module_' + item.moduleCode + '" class="listname_listnav">' + item.moduleName + '<div class="navlistbtn"></div></h3>\
                          <ul class="listnav" style="display: none;white-space:nowrap;">\
                              <li id="moduleLi_' + item.moduleCode + '" class="listnavli">\
                              </li>\
                           </ul>';
    });
    $('#accordion').html(accordionHtml);

    // 折叠菜单点击事件
    $('.listname_listnav').click(function () {
        var moduleCode = $(this).prop('id').substr('module_'.length);
        var $navlistbtnDown = $('#accordion .navlistbtn.down');
        if ($navlistbtnDown.length > 0) {
            var oldModuleCode = $navlistbtnDown.parent().prop('id').substr('module_'.length);
            if (moduleCode != oldModuleCode) {
                // 收起其他打开的折叠菜单
                $('#accordion .listname_listnav:not(:last)').find('.navlistbtn.down').parent().css('border-bottom', '0px solid #D9D9D9');
                $navlistbtnDown.parent().next('.listnav').stop(true).slideToggle();
                $navlistbtnDown.toggleClass("down");
            }
        }
        // 切换当前的折叠菜单
        $('#accordion .listname_listnav:not(:last)').find('.navlistbtn.down').parent().css('border-bottom', '0px solid #D9D9D9');

        $(this).next('.listnav').stop(true).slideToggle();
        $(this).find('.navlistbtn').toggleClass("down");

        $('#accordion .listname_listnav:not(:last)').find('.navlistbtn.down').parent().css('border-bottom', '1px solid #D9D9D9');

        var moduleTree = $(this).next('.listnav').find('[id^="moduleTree_"]');
        if (moduleTree.length == 0) {

            moduleTreeView(moduleCode);
        }
    });
    resizeLeftnavcard();
}

function resizeLeftnavcard() {
    var $listname_listnav = $('.listname_listnav');
    var listname_listnav_height = 0;
    $.each($listname_listnav, function (idx, item) {
        listname_listnav_height += $(item).outerHeight();
    });
    var accheight = $('.leftnavcard').height() - 80 - listname_listnav_height;
    $('#accordion .listnav').css({
        'overflow': 'auto',
        'height': accheight + 'px',
        'margin': '0'
    });
}

/**
 * 构造菜单树
 *
 * @param moduleCode
 */
function moduleTreeView(moduleCode) {
    // 取消其他菜单选中
    $('#accordion .tree-item.tree-selected').removeClass('tree-selected');

    // 加载折叠面板菜单
    $('#moduleLi_' + moduleCode).html('<ul id="moduleTree_' + moduleCode + '" style="width: 500px;"></ul>');
    var $moduleTree = $('#moduleTree_' + moduleCode);
    $moduleTree.ace_tree({
        loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
        'open-icon': 'ace-icon fa fa-chevron-down',
        'close-icon': 'ace-icon fa fa-chevron-right',
        'itemSelect': true,
        'folderSelect': false,
        'multiSelect': false,
        'selected-icon': false,
        'unselected-icon': false,
        'folder-open-icon': 'ace-icon tree-plus',
        'folder-close-icon': 'ace-icon tree-minus',
        'cacheItems': true,
        dataSource: function (options, callback) {
            var $data = null;

            if (!("name" in options) && !("type" in options)) {
                callback({data: queryModuleData(moduleCode)});//
                return;
            } else if ("type" in options && options.type == "folder") {
                if ("additionalParameters" in options && "children" in options.additionalParameters)
                    $data = queryModuleData(options.additionalParameters.id);//点击父节点，加载子节点
                else {
                    $data = {}
                }
            }
            if ($data != null) {//this setTimeout is only for mimicking some random delay
                callback({data: $data});
            }
        }
    }).on('selected.fu.tree', function (event, data) {
        jumpPage(data.target.additionalParameters.modulePath);
    }).on('deselected.fu.tree', function (event, data) {
        var $selectedModuleTree = $('#accordion .navlistbtn.down').parent().next('.listnav').find('[id^="moduleTree_"]');
        if ($selectedModuleTree.length > 0) {
            $selectedModuleTree.tree('selectItem', $('#' + data.target.additionalParameters.id));
        }
    }).on('closed.fu.tree', function (event, data) {
        // reloadJqGrid('json');
    });

    // 默认展开根节点
    $moduleTree.tree('openFolder', $moduleTree.find('.tree-branch')[1]);
}

/**
 * 获取菜单树数据
 *
 * @param parentCode
 * @returns {*}
 */
function queryModuleData(parentCode) {
    var treeData = null;
    $.ajax({
        url: ctx + '/tbSysModule/queryTreeModule?number=' + Math.random(),
        async: false,
        type: 'post',
        dataType: 'json',
        data: {
            parentCode: parentCode
        },
        success: function (data) {
            if (data.success) {
                treeData = data.result;
            }
        }
    });
    return treeData;
}

/**
 * 跳转页面
 *
 * @param url
 * @param pageType
 */
function jumpPage(url, pageType, obj) {
    if (pageType && pageType == 1) {
        // 显示首页时，不显示左侧菜单
        if ($('.leftbtnbox').css('left') != '0px') {
            $('.leftbtnbox .leftbtn').trigger('click');
        }
        // 切换导航选中样式
        triggerNavigationCss(obj)
    }
    if (url.match(/^page\//)) {
        url = ctx + '/index/jumpPage/' + encodeURIComponent(encodeURIComponent(url));
    }
    $('#portal_iframe').attr('src', url);
}

/**
 * 切换导航选中样式
 *
 * @param obj
 */
function triggerNavigationCss(obj) {
    $('#navigation .item.choose').removeClass('choose');
    $(obj).addClass('choose');
}



